package com.lg.service.impl;

import java.io.File;
import java.sql.SQLException;
import java.util.List;

import com.lg.dao.Example;
import com.lg.dao.criteria.AngelPicturesCriteria;
import com.lg.model.AngelPictures;
import com.lg.model.exception.BusinessException;
import com.lg.model.exception.OtherException;
import com.lg.serivce.AngelPicturesService;
import com.lg.util.PageUtilBean;

public class AngelPicturesServiceImpl extends GenericServiceImpl<AngelPictures>
		implements AngelPicturesService {
	/**
	 * @param promoterId
	 * @param currentPage
	 * @return 查询选手下的图片集合
	 */
	public PageUtilBean findPromoterPhotos(String promoterId, String currentPage) {

		Example<AngelPicturesCriteria> ee = new Example<AngelPicturesCriteria>(
				AngelPicturesCriteria.class);
		AngelPicturesCriteria c = ee.createCriteria();
		c.andPromoterIdEqualTo(promoterId);

		int count = countPromoterPhotos(ee);

		PageUtilBean pageUtilBean = new PageUtilBean();
		pageUtilBean.setOnePageCount("12");
		pageUtilBean.setResultCount(count);
		pageUtilBean.setCurrentPage(currentPage);
		int n = pageUtilBean.getStart();
		try {
			List list = this.getBaseDAO().getAngelPicturesDAO()
					.selectListByStatementId("promoterPhotos", promoterId, n,
							pageUtilBean.getOnePageCount());
			if (list != null)
				pageUtilBean.setModelList(list);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return pageUtilBean;
	}

	private int countPromoterPhotos(Example e) {
		int n = 0;
		try {
			n = this.getBaseDAO().getAngelPicturesDAO().countByExample(e);
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return n;
	}

	public void delPhoto(String pictureId, String filepath) {

		if (pictureId == null) {
			throw new BusinessException("相片id不能为空");
		}

		AngelPictures p = new AngelPictures();
		p.setPictureId(pictureId);
		try {
			this.getBaseDAO().getAngelPicturesDAO().deleteByPrimaryKey(p);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		File f = new File(filepath);
		f.deleteOnExit();
	}

	@Override
	public void addBatchePictures(List<AngelPictures> list)
			throws BusinessException, OtherException {
		if (!list.isEmpty()) {
			try {
				getBaseDAO().getAngelPicturesDAO().insertBatch(list);
			} catch (SQLException e) {
				throw new OtherException(e.getMessage());
			}
		}
	}
}